package admin

import (
	"crypto/md5"
	"encoding/hex"
	"parking-lot-go-admin/model"
	"strconv"
	"time"
)

type AdminTokenStruct struct {
	Id           int       `json:"id" gorm:"type:int(11) auto_increment; NOT NULL; primary_key"`
	AdminId      int       `json:"admin_id" gorm:"type:int(11)"`
	AccessToken  string    `json:"access_token" gorm:"type:varchar(255)"`
	RefreshToken string    `json:"refresh_token" gorm:"type:varchar(255)"`
	Expires      time.Time `json:"expires" gorm:"type:datetime"`
}

func (c *AdminTokenStruct) TableName() string {
	return "admin_token"
}

func (c *AdminTokenStruct) CreateAccessToken(id int) error {
	accessToken := generateToken(id)
	refreshToken := generateToken(id)
	expires := time.Now().Add(2 * time.Hour)
	err := model.CreateModelData(
		model.Db,
		c.TableName(),
		map[string]interface{}{
			"admin_id":      id,
			"access_token":  accessToken,
			"refresh_token": refreshToken,
			"expires":       expires.Format("2006-01-02 15:04:05"),
		},
	)

	return err
}

// 更新生成token
func (c *AdminTokenStruct) UpdateAccessToken(id int) (string, string, string) {
	accessToken := generateToken(id)
	refreshToken := generateToken(id)
	expires := time.Now().Add(2 * time.Hour)
	model.UpdateModelData(
		model.Db,
		c.TableName(),
		map[string]interface{}{
			"admin_id": id,
		},
		map[string]interface{}{
			"access_token":  accessToken,
			"refresh_token": refreshToken,
			"expires":       expires.Format("2006-01-02 15:04:05"),
		},
	)

	return accessToken, refreshToken, expires.Format("2006/01/02 15:04:05")
}

// 生成token
func generateToken(id int) string {
	idStr := strconv.Itoa(id)
	randomString := model.GenerateRandomString(10)            // 生成随机字符串
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10) // 获取当前时间戳
	input := randomString + timestamp + idStr                 // 构建输入字符串

	hasher := md5.New()                         // 创建MD5哈希对象
	hasher.Write([]byte(input))                 // 计算哈希值
	hash := hex.EncodeToString(hasher.Sum(nil)) // 获取哈希摘要并转换为十六进制字符串
	return hash
}
